package com.etc.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.util.RegexUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.etc.entity.User;
import com.etc.service.UserService;
import com.etc.util.MD5Util;
import com.etc.util.Message;
import com.etc.util.PageData;

@Controller
@RequestMapping(value = "userapi")
public class UserController {
    @Resource
    private UserService us;

    @Resource(name = "message")
    private Message msg;

    private Logger log = Logger.getLogger(UserController.class);

    /**
     * 删除的方法
     *
     * @param userid
     * @return
     */
    @RequestMapping(value = "user/{userId}", method = RequestMethod.DELETE)
    @ResponseBody
    public Message deleteByPrimaryKey(@PathVariable(value = "userId") int userid, HttpSession session) {
        // log.info("删除的方法");
        // 增加了管理员不能自己删自己得功能
        User user = us.selectByPrimaryKey(userid);
        if (session.getAttribute("username") != null && session.getAttribute("username").equals(user.getUserName())) {
            msg.setMsg("该删除操作违规");
        } else {
            boolean flag = us.deleteByPrimaryKey(userid);
            if (flag) {
                msg.setMsg("删除成功");
            } else {
                msg.setMsg("删除失败");
            }
        }
        return msg;
    }

    /**
     * 添加的方法
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.POST)
    @ResponseBody
    public Message insertSelective(@RequestBody User user) {
        System.out.println("增加" + user);
        boolean flag = us.insertSelective(user);
        if (flag) {
            msg.setMsg("添加成功");
        } else {
            msg.setMsg("添加失败");
        }
        return msg;
    }

    /**
     * 查询单个用户的方法
     *
     * @param
     * @return
     */
    @RequestMapping(value = "user/{userid}", method = RequestMethod.GET)
    @ResponseBody
    public User selectByPrimaryKey(@PathVariable(value = "userid") int userid) {
        // log.info("查询单个");
        User user = us.selectByPrimaryKey(userid);
        return user;
    }

    /**
     * 修改的方法
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.PUT)
    @ResponseBody
    public Message updateByPrimaryKeySelective(User user, HttpSession session) {
        msg.setMsg("");
        if (us.getOtherUser(user)) {
            msg.setMsg("该用户名已存在,修改失败");
        } else {
            String newPwd = MD5Util.getEncodeByMd5(user.getUserPwd());
            user.setUserPwd(newPwd);
            boolean flag = us.updateByPrimaryKeySelective(user);
            //判断session的名字是否和修改后的用户名一致
            User user1 = us.selectByPrimaryKey(user.getUserId());
            session.setAttribute("userInfo", user1);
            msg.setMsg("修改成功");
        }

        return msg;
    }

    @RequestMapping(value = "user", method = RequestMethod.GET)
    @ResponseBody
    public PageData<User> selectByPage(int page, int limit, String content) {
        if (content == null) {
            content = "";
        }
        PageData<User> pg = us.selectByPage(page, limit, content);
        pg.setCode(0);
        pg.setMsg("");
        return pg;
    }

    /**
     * 后台管理员登录校验的方法
     *
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "adminlogin", method = RequestMethod.GET)
    @ResponseBody
    public Message selectByUser(User user, HttpServletRequest request) {
        String pwd = MD5Util.getEncodeByMd5(user.getUserPwd());
        user.setUserPwd(pwd);
        //log.info("查询单个");
        boolean flag = us.selectByUser(user);
        if (flag) {
            request.getSession().setAttribute("username", user.getUserName());
            msg.setMsg("校验成功");
        } else {
            msg.setMsg("校验失败");
        }
        return msg;
    }

    /**
     * 前端登录框失焦事件
     * szh
     *
     * @param userName
     * @return
     */
    @RequestMapping(value = "usercheck", method = RequestMethod.GET)
    @ResponseBody
    public Message selectByUserName(String userName) {
        msg.setMsg("");
        // log.info("传来的用户名" + userName);
        boolean flag1 = us.selectByUserName(userName);
        User flag2 = us.selectByTel(userName);
        User flag3 = us.selectByEmail(userName);
        if (!flag1 && flag2 == null && flag3 == null) {
            msg.setMsg("该用户不存在");
        }
        return msg;
    }

    /**
     * 前端密码登录校验的方法
     * szh
     * 前端传过来的user只有username和userpwd
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "frontlogin", method = RequestMethod.GET)
    @ResponseBody
    public Message checkByUser(User user, HttpSession session, HttpServletResponse response) {
        log.info("表单值" + user);
        int n = RegexUtil.validateName(user.getUserName());
        User exchange = new User();
        switch (n) {
            case 1: {
                exchange.setUserName(user.getUserName());
                break;
            }
            case 2: {
                exchange.setTel(user.getUserName());
                break;
            }
            case 3: {
                exchange.setEmail(user.getUserName());
                break;
            }
        }
        String pwd = MD5Util.getEncodeByMd5(user.getUserPwd());
        exchange.setUserPwd(pwd);
        //log.info("查询单个");
        User validatedUser = us.checkByUser(exchange);
        // log.info("查数据库" + validatedUser);
        if (validatedUser != null) {
            session.setAttribute("userInfo", validatedUser);
            Cookie cookie = new Cookie("randomcookies", user.getTel() + user.getUserPwd());
            cookie.setMaxAge(60 * 60);
            response.addCookie(cookie);
            msg.setMsg("校验成功");
        } else {
            msg.setMsg("校验失败");
        }
        return msg;
    }

    /**
     * 前端登录控制器
     * 史泽浩
     *
     * @param
     * @return
     */
    @RequestMapping(value = "tofrontlogin/{action}")
    public String tofrontlogin(@PathVariable("action") String action) {
        //log.info(action);
        return "front" + action;
    }

    /**
     * 前端界面控制器
     *
     * @param
     * @return
     */
    @RequestMapping(value = "tohome")
    public String tohome() {
        return "home";
    }

    /**
     * 前端注册的方法
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public Message insertselective(User user) {
        boolean flag = us.insertUser(user);
        if (flag) {
            msg.setMsg("添加成功");
        } else {
            msg.setMsg("添加失败");
        }
        return msg;
    }

    @RequestMapping(value = "checksession")
    public String checksession(HttpSession session) {
        if (session.getAttribute("username") != null) {
            return "redirect:/admin/views/information.jsp";
        } else {
            return "frontlogin";
        }

    }
}
